package main

import (
	"fmt"
	"time"
)

func main() {
	// time use
	timer1 := time.NewTimer(2 * time.Second)
	t1 := time.Now()
	fmt.Printf("t1: %v\n", t1)
	t2 := <-timer1.C // 2s after
	fmt.Printf("t2: %v\n", t2)

	// 2 验证 timer 只能响应一次
	//timer2 := time.NewTimer(time.Second)
	//for {
	//	<-timer2.C
	//	fmt.Println("时间到")
	//}

	//  3.timer实现延时的功能
	fmt.Println(time.Now().Unix())
	time.Sleep(time.Second)
	fmt.Println(time.Now().Unix())
	time3 := time.NewTimer(2 * time.Second)
	<-time3.C
	fmt.Println("2秒到")

	// 4.停止定时器
	timer4 := time.NewTimer(2 * time.Second)
	go func() {
		<-timer4.C
		fmt.Println("定时器执行了")
	}()
	b := timer4.Stop()
	if b {
		fmt.Println("timer4已经关闭")
	}

	// 5.重置定时器
	fmt.Println(time.Now().Unix(), "2s after")
	timer5 := time.NewTimer(2 * time.Second)
	timer5.Reset(1 * time.Second)
	fmt.Println(time.Now().Unix(), "change 1s")
	fmt.Println(<-timer5.C)

	for {
	}
}
